package pl.edu.pw.mini.java2.Communicator.Client;

import java.io.*;
import java.util.concurrent.*;

public class WriterWorker extends Thread {
	private DataOutputStream output;
	private LinkedBlockingQueue<Message> buffer = new LinkedBlockingQueue<Message>();

	public WriterWorker(DataOutputStream output) {
		this.output = output;
	}

	public void close() {
		buffer.clear();
		this.interrupt();
		try {
			output.close();
		} catch (IOException e) {
		}
		output = null;
	}

	@Override
	public void run() {
		try {
			while (true) {
				buffer.take().send(output);
			}
		} catch (InterruptedException ex) {
			System.out.println("Interrupted Exception in writer!");
		} catch (IOException ex) {
			System.out.println("IO error In client writer!");
			ex.printStackTrace();
		}
	}

	public void sendMessage(Message m) {
		try {
			buffer.put(m);
		} catch (InterruptedException ignored) {
		}
	}
}
